package com.xwd.web;

import com.xwd.domain.Users;
import com.xwd.service.UsersService;
import com.xwd.service.impl.UsersServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //调用service
        UsersService service = new UsersServiceImpl();
        Users user = service.login(username, password);
        if(user!=null){
            //登陆成功，跳转页面并存session
            HttpSession session = req.getSession();
            session.setAttribute("user",user);
            resp.sendRedirect("/index.jsp");
        }else {
            //登陆失败，重新跳转并提示信息
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer = resp.getWriter();
            writer.println("<script>location.href='login.jsp';alert('用户名不对或密码不正确');</script>");
        }
    }
}
